/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.filter;

import com.google.inject.Inject;
import com.google.inject.Injector;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import th.config.ableContextListener;
import th.dao.KodTransaksiDAO;
import th.dao.PenggunaDAO;
import th.manager.PageAuditManager;
import th.model.KodTransaksi;
import th.model.LogPenggunaApplikasi;
import th.model.Pengguna;

/**
 *
 * @author fikri
 */
public class PageFilter implements Filter {

    private static final boolean debug = true;
    public static final String DEFAULT_LOGIN_PATH = "/login";
    private static String loginPath;
    private static String publicPath;
    private static String kodTransaksi;
    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    private static final Logger LOG = Logger.getLogger(PageFilter.class);
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;   

    public PageFilter() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

//	if (debug) log("PageFilter:doFilter()");

        HttpServletRequest r = (HttpServletRequest) request;
        HttpSession session = r.getSession();
        String userId = (String) session.getAttribute("_KEY_USER");
        String reqPath = r.getRequestURI();

        Throwable problem = null;
        StringBuilder s = getSingleParameterMap(r);        
        

        try {

//            if (debug){
//			LOG.debug("REQ:" + reqPath + " from " + r.getRemoteAddr() + " begin");
//		}

            if (loginPath.equals(reqPath)
                    || reqPath.endsWith("js") || reqPath.endsWith("jar")
                    || reqPath.endsWith("css") || reqPath.endsWith("xml")
                    || reqPath.endsWith("properties") || reqPath.endsWith("gif")
                    || reqPath.endsWith("png") || reqPath.endsWith("swf")
                    || reqPath.endsWith("jpg") || reqPath.endsWith("cur")) {
                chain.doFilter(request, response);
                return;
            }

            Injector injector = ableContextListener.getInjector();
            PenggunaDAO penggunaDAO = injector.getInstance(PenggunaDAO.class);
            KodTransaksiDAO kodTransaksiDAO = injector.getInstance(KodTransaksiDAO.class);
            PageAuditManager pageAuditService = injector.getInstance(PageAuditManager.class);
            if (userId != null) {
                    Pengguna pengguna = penggunaDAO.findById(userId); 
                    if (pengguna != null) userId = pengguna.getIdPengguna();
                }           
            
            LogPenggunaApplikasi log = new LogPenggunaApplikasi();
            log.setIdPguna(userId);
            log.setTarikhMasuk(new Date());
            log.setUrl(reqPath);
            if (s.length() > 1000){
                log.setNilaiDalaman1(s.substring(0, 1000).toString());
            } else {
                log.setNilaiDalaman1(s.toString());
            }
            if (kodTransaksi != null && !"".equals(kodTransaksi)) {
                KodTransaksi kt = kodTransaksiDAO.findById(kodTransaksi);
                log.setTransaksi(kt);
            }
           
            pageAuditService.save(log);


            chain.doFilter(request, response);
        } catch (Throwable t) {
            // If an exception is thrown somewhere down the filter chain,
            // we still want to execute our after processing, and then
            // rethrow the problem after that.
            problem = t;
            t.printStackTrace();
        }

        if (problem != null) {
            if (problem instanceof ServletException) {
                throw (ServletException) problem;
            }
            if (problem instanceof IOException) {
                throw (IOException) problem;
            }
            sendProcessingError(problem, response);
        }
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter
     */
    public void destroy() {
    }

    /**
     * Init method for this filter
     */
    @Override
    public void init(FilterConfig filterConfig) {
        //String ctxPath = filterConfig.getServletContext().getContextPath();
        String ctxPath = "";
        loginPath = ctxPath + DEFAULT_LOGIN_PATH;
        publicPath = ctxPath + "/pub";
        this.filterConfig = filterConfig;
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("PageFilter()");
        }
        StringBuffer sb = new StringBuffer("PageFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
        String stackTrace = getStackTrace(t);

        if (stackTrace != null && !stackTrace.equals("")) {
            try {
                response.setContentType("text/html");
                PrintStream ps = new PrintStream(response.getOutputStream());
                PrintWriter pw = new PrintWriter(ps);
                pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

                // PENDING! Localize this for next official release
                pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                pw.print(stackTrace);
                pw.print("</pre></body>\n</html>"); //NOI18N
                pw.close();
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                PrintStream ps = new PrintStream(response.getOutputStream());
                t.printStackTrace(ps);
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        }
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch (Exception ex) {
        }
        return stackTrace;
    }

    public void log(String msg) {
        filterConfig.getServletContext().log(msg);
    }
    
     private StringBuilder getSingleParameterMap(HttpServletRequest request) {
        kodTransaksi = "";
        StringBuilder params = new StringBuilder();        
        for (Enumeration en = request.getParameterNames();en.hasMoreElements();) {
            String name = (String) en.nextElement();            
            String value = request.getParameter(name);       
            if (StringUtils.isNotBlank(name) && StringUtils.isBlank(kodTransaksi)) {
                setKodTrans(name);            
            }
            if (name.startsWith("deposit") || name.startsWith("haji") || name.startsWith("taha")) {
                params.append(name).append("=").append(StringUtils.isNotBlank(value) ? value.trim() : "").append("|");
            }            
        }         
        return params;
    }   
     
     private void setKodTrans(String name) {
        if ("semakPendaftaranHaji".equals(name)) { //SEMAKAN PENDAFTARAN HAJI
            kodTransaksi = "HJ001";
        } else if ("semakTawaranHaji".equals(name)) { //SEMAKAN TAWARAN TUNAI HAJI
            kodTransaksi = "HJ002";
        } else if ("HajjReg_Step5".equals(name)) { //PENDAFTARAN HAJI - Check
            kodTransaksi = "HJ003";
        } else if ("slipRegistration".equals(name)) { //TODO : CETAKAN SLIP PENDAFTARAN HAJI - Check
            kodTransaksi = "HJ004";
        } else if ("surat".equals(name)) { //TODO : CETAKAN SURAT TAWARAN TUNAI HAJI - check
            kodTransaksi = "HJ005";
        } else if ("HajjResp_Step6".equals(name) || "HajjResp_Step7".equals(name)) { //TODO :JAWAB TAWARAN TUNAI HAJI - Check
            kodTransaksi = "HJ006";
        } else if ("HajjSubD_Step3".equals(name)) { //TODO :TOLAK TANGGUNGAN HAJI - check
            kodTransaksi = "HJ007";
        } else if ("SuratPenerbangan".equals(name)) { //TODO : CETAKAN SURAT JADUAL PENERBANGAN
            kodTransaksi = "HJ008";
        } else if ("saveUpdateProfile".equals(name)) { //KEMASKINI PROFIL
            kodTransaksi = "DP001";
        } else if ("checkBalance".equals(name)) { //PERTANYAAN BAKI
            kodTransaksi = "DP002";
        } else if ("Transfer_Step4".equals(name)) { //PINDAHAN SIMPANAN
            kodTransaksi = "DP003";
        } else if ("checkStatement".equals(name)) { //PENYATA AKAUN
            kodTransaksi = "DP004";
        } else if ("addAcc".equals(name) || "deleteAkaun".equals(name)) { //KEMASKINI AKAUN
            kodTransaksi = "DP005";
        } else if ("getPenyataKad".equals(name)) { //PENYATA KAD
            kodTransaksi = "DP006";
        } else if ("saveFavAcc".equals(name)) { //TAMBAH FAV AKAUN
            kodTransaksi = "DP007";
        } else if ("TahaReg_Step3".equals(name)) { //PENDAFTARAN KELAB TAHA/TAHA@U --- check 
            kodTransaksi = "TH001";
        } else if ("showPertanyaanDetail".equals(name)) { //PERTANYAAN KELAB TAHA/TAHA@U
            kodTransaksi = "TH002";
        } else {
            kodTransaksi = "";
        }
    }
    
}
